import {Component, OnInit} from '@angular/core';
import {TipService} from "../../../services/tip.service";
import {ExtendHttpService} from "../../../services/extend-http.service";
import {Router} from "@angular/router";

@Component({
  selector: 'app-change-password',
  templateUrl: './change-password.component.html',
  styleUrls: ['./change-password.component.css']
})
export class ChangePasswordComponent implements OnInit {

  submitType = true;
  tipType = 'error';
  pwd = {old_pwd: '', login_pwd: '', login_pwd1: ''};
  isLoading = false;

  constructor(private tipService: TipService,
              private extendHttp: ExtendHttpService,
              private router: Router) {
  }

  ngOnInit() {
    cBack =()=> {
      $('#btn-back').trigger('click');
    }
  }

  submitData() {
    if (!this.pwd.old_pwd.trim()) {
      this.tipService.change(true, '请输入旧密码');
      return;
    }

    if (!this.pwd.login_pwd.trim()) {
      this.tipService.change(true, '请输入新密码');
      return;
    }

    if (!this.pwd.login_pwd1.trim()) {
      this.tipService.change(true, '请再次输入新密码');
      return;
    }
    if (this.pwd.login_pwd.trim() != this.pwd.login_pwd1.trim()) {
      this.tipService.change(true, '两次密码输入不一致');
      return;
    }

    // 密码md5加密
    let params2 = Object.assign({}, this.pwd);
    params2.old_pwd = hex_md5(params2.old_pwd);
    params2.login_pwd = hex_md5(params2.login_pwd);
    this.isLoading = !this.isLoading;
    this.extendHttp.post('/agentApp/info/changePwd', params2).subscribe(response => {
      let res = response.json();
      if (res['code'] === '0') {
        this.isLoading = !this.isLoading;
        this.tipType = 'success';
        this.tipService.change(true, res['message']);
        setTimeout(() => {
          this.router.navigateByUrl('/login');
        }, 1500);
      } else if (res['code'] === '-2001') {
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
        setTimeout(() => {
          this.router.navigateByUrl('/login');
        }, 1500);
      } else {
        this.isLoading = !this.isLoading;
        this.tipType = 'error';
        this.tipService.change(true, res['message']);
      }
    }, error => {
      this.isLoading = !this.isLoading;
      this.tipType = 'error';
      this.tipService.change(true, '系统繁忙，操作失败！');
    });
  }

}
